package com.weng.coder.common.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件操作工具类
 * @author wengzhonghui
 *
 */
public class FileUtil {

	private static final int BUFFER_SIZE = 1024;

	
	/**
	 * 复制上传的文件到指定目录
	 * @param src
	 * @param dst
	 */
	public static void copy(InputStream in, File dst) {
		OutputStream out = null;
		try {
			if (dst.exists()) {
				out = new BufferedOutputStream(new FileOutputStream(dst, true),
						BUFFER_SIZE);
			} else {
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
			}
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}
	
	public static void redirectOut(String fileName) throws FileNotFoundException {
		FileOutputStream fos = new FileOutputStream(fileName);
		PrintStream ps = new PrintStream(fos);
		System.setOut(ps);
	}

	public static String getFileContent(String fileName) throws IOException {
		StringBuffer sb = new StringBuffer();
		File f = new File(fileName);
		FileReader r = new FileReader(f);
		BufferedReader br = new BufferedReader(r);
		String line = br.readLine();
		while (line != null) {
			sb.append(line).append("\n");
			line = br.readLine();
		}
		r.close();
		br.close();
		return sb.toString();
	}
	
	public static void main(String[] args) throws IOException{
		String filePath = "D:\\temp\\333\\1.txt";
		getFieldBySql(getFileContent(filePath));
	}
	public static void getFieldBySql(String sql){
		if(!StringUtils.isEmpty(sql)){
			sql = sql.toLowerCase();
			sql = sql.replace("`", "");
			String[] tableSqls = sql.split("create ");
			if(tableSqls.length>0){
				for(String tableSql : tableSqls){
					if(tableSql.indexOf("table ")<0){
						continue;
					}
					String tableName = getTableNameByCreateSQL(tableSql);
					if(!StringUtils.isEmpty(tableName)){
						
						String tableRemarks = getTableRemarksByCreateSQL(tableSql);
//						System.out.println(tableName);
//						System.out.println(tableRemarks);
						System.out.println(getColumnByCreateSQL(tableSql));
					}
					
//					System.out.println(tableSql);
					System.out.println("##################");
				}
			}
		}
	}
	
	/**
	 * 通过建库脚本获取表名
	 * @return
	 */
	private static String getTableNameByCreateSQL(String createSql){
		if(!StringUtils.isEmpty(createSql) && createSql.indexOf("(")>0){
			String sqlBegin = createSql.substring(0,createSql.indexOf("(")); // 得到create table coder_column (
			sqlBegin = sqlBegin.replace("create", "");
			sqlBegin = sqlBegin.replace("table", "");
			sqlBegin = sqlBegin.replace("(", "");
			sqlBegin = sqlBegin.trim();
			return sqlBegin;
		}
		return null;
	}
	
	/**
	 * 通过建库脚本获取表列名
	 * @return
	 */
	private static String getColumnByCreateSQL(String createSql){
		if(!StringUtils.isEmpty(createSql)){
			
			if(createSql.indexOf(";")>0){
				createSql = createSql.substring(0,createSql.indexOf(";"));
			}
			int indexFirst = createSql.indexOf("(") + 1;
			int indexLast = createSql.lastIndexOf(")");
			if(indexFirst > 0 && indexLast > indexFirst){
				createSql = createSql.substring(indexFirst,indexLast);
			}
			String[] columnStrs = createSql.split(",");
			for(String columnSql : columnStrs){
				getColumnBySql(columnSql);
			}
//			System.out.println(createSql);
			
		}
		return null;
	}
	
	/**
	 * 通过列定义获取列名，数据类型，注释等信息
	 * @param columnSql 如 name varchar(255) collate utf8_bin default '' comment '列名',
	 * @return
	 */
	public static Map<String,String> getColumnBySql(String columnSql){
		if(!StringUtils.isEmpty(columnSql)){
			columnSql = columnSql.trim();
			String remark = getColumnRemarks(columnSql);
			String[] strs = columnSql.split(" ");
			if(strs.length>2){
				String columnName = strs[0];
				String columnType = strs[1];
				if(columnType.indexOf("(")>0){
					columnType = columnType.substring(0, columnType.indexOf("("));
				}
				Map<String,String> data = new HashMap<>();
				data.put("columnName", columnName);
				data.put("columnType", columnType);
				data.put("remark", remark);
				System.out.println(columnName + "@" + columnType + "@" + remark );
			}
		}
		return null;
	}
	
	/**
	 * 获取列注释
	 * @param columnSql 如name varchar(255) collate utf8_bin default '' comment '列名',
	 * @return
	 */
	private static String getColumnRemarks(String columnSql){
		if(!StringUtils.isEmpty(columnSql) && columnSql.indexOf("comment")>0){
			columnSql = columnSql.substring(columnSql.indexOf("comment") + "comment".length());
			columnSql = columnSql.replaceAll("'", "");
			columnSql = columnSql.replaceAll(",", "");
			return columnSql.trim();
		}
		return "";
	}
	
	/**
	 * 通过建库脚本获取表名
	 * @return
	 */
	private static String getTableRemarksByCreateSQL(String createSql){
		if(!StringUtils.isEmpty(createSql) && createSql.indexOf(")")>0){
			String sqlBegin = createSql.substring(createSql.lastIndexOf(")")); // 得到create table coder_column (
			if(createSql.indexOf("comment")>0){
				createSql = createSql.substring(createSql.lastIndexOf("comment") + "comment".length());
				if(createSql.indexOf("'")>0){
					createSql = createSql.substring(createSql.indexOf("'") + 1);
				}
				if(createSql.indexOf("'")>0){
					createSql = createSql.substring(0,createSql.indexOf("'"));
				}
				String remarks = createSql.replace("=", "");
				remarks = remarks.replaceAll("'", "");
				remarks = remarks.replaceAll("\"", "");
				remarks = remarks.replaceAll(";", "");
				remarks = remarks.trim();
				return remarks;
			}
			return sqlBegin;
		}
		return "";
	}
	
	public static byte[] fileToBytes(String filePath) {
		File file = new File(filePath);
		return fileToBytes(file);
	}
	/**
	 * 通某个路径下的文件获取byte文件流
	 * @param filePath
	 * @return
	 */
	public static byte[] fileToBytes(File file) {
        byte[] buffer = null;
        
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;

        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();

            byte[] b = new byte[1024];

            int n;

            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            
            buffer = bos.toByteArray();
        } catch (FileNotFoundException ex) {
        } catch (IOException ex) {
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException ex) {
            } finally{
                try {
                    if(null!=fis){
                        fis.close();
                    }
                } catch (IOException ex) {
                }
            }
        }
        
        return buffer;
    }

	public static void mkdirs(String path) {
		File folder = new File(path);
		if (!folder.exists()){
			folder.mkdirs();
		}
			
	}

	public static void mkdir(File file) {
		if (file.getParentFile().exists()) {
			file.mkdir();
		} else {
			mkdir(file.getParentFile());
			file.mkdir();
		}
	}

	/**
	 * 将inputStream 读出byte数组中
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	public static byte[] readInputStream(InputStream inStream) throws IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[BUFFER_SIZE];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		inStream.close();
		return outStream.toByteArray();
	}

	public static final String readInputStream2String(InputStream in) throws UnsupportedEncodingException, IOException {
		if(in == null) {
			return "";
		}
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[BUFFER_SIZE];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n, "UTF-8"));
		}
		return out.toString();
	}

}
